const { semver, error } = require("@vue/cli-shared-utils");
const requiredVersion = require("@vue/cli-service/package.json").engines.node;
const Service = require("@vue/cli-service/lib/Service");
const {
  runnedStopStrategy,
  registryAppName,
  registryedAppName,
  registyCustomEnv,
  argvWrapper,
  ui
} = require("./service-help");
const {
  initNpmConfigParams,
  getSubApps,
  getPredefineApps
} = require("./utils");

const execute = (argv) => {
  const _argv = argv;
  if (
    !semver.satisfies(process.version, requiredVersion, {
      includePrerelease: true
    })
  ) {
    error(
      `You are using Node ${process.version}, but vue-cli-service requires Node ${requiredVersion}`
    );
    process.exit(0);
  }
  const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd());
  const [_cmder, ...rest] = _argv;

  const _bootstrap = () => {
    const [_f, ..._r] = _argv;
    const rawArgv = [_f, ...argvWrapper(_r)];
    const args = require("minimist")(rawArgv, { boolean: getPredefineApps() });
    const command = args._[0];
    initNpmConfigParams(args);
    console.log(command, args, rawArgv);
    service
      .run(command, args, rawArgv)
      .then(() => {
        if (runnedStopStrategy(command)) {
          process.exit(0);
        }
      })
      .catch((err) => {
        error(err);
        process.exit(-1);
      });
  };

  const _ui = () => {
    ui(_cmder)
      .then(() => {
        registyCustomEnv(_cmder, rest);
        _bootstrap();
      })
      .catch((e) => console.log(e));
  };

  if (rest && rest.length > 0) {
    const apps = getSubApps();
    const idx = _argv.findIndex((item) => apps.includes(item));
    if (idx >= 0) {
      registryAppName(_argv[idx]);
      registryedAppName(_argv, idx);
      registyCustomEnv(_cmder, rest);
      _bootstrap();
    } else {
      _ui();
    }
  } else {
    _ui();
  }
};

module.exports = {
  execute
};
